#include "stdafx.h"
#include "HostIP.h"

#include "CommonFunc.h"

#include <list>
#include <string>
#include <stdexcept>
#include <sstream>

using std::list;
using std::string;
using std::stringstream;

void HostIP::getHostIP(std::list<std::string> &hostIPList) const
{
	SECURITY_ATTRIBUTES sa;
	sa.bInheritHandle = TRUE;
	sa.lpSecurityDescriptor = NULL;
	sa.nLength = sizeof(sa);

	HANDLE pipeReadHandle, pipeWriteHandle;
	if(!CreatePipe(
		&pipeReadHandle, 
		&pipeWriteHandle,
		&sa,
		0))
	{
		throw std::runtime_error("Create pipe for ipconfig error");
	}

	STARTUPINFO startupInfo;
	PROCESS_INFORMATION processInfo;
	std::wstring cmdProcessName(L"ipconfig"); 

	memset(&startupInfo, 0, sizeof(startupInfo));
	startupInfo.cb = sizeof(startupInfo);
	startupInfo.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
	startupInfo.wShowWindow = SW_HIDE;
	startupInfo.hStdOutput = pipeWriteHandle;

	if(!CreateProcess(
		NULL,
		const_cast<LPWSTR>(cmdProcessName.c_str()),
		&sa,
		&sa,
		TRUE,
		0,
		NULL,
		NULL,
		&startupInfo,
		&processInfo))
	{
		throw std::runtime_error("Create ipconfig process error");
	}

	const int bufferSize = 5000;
	char buffer[bufferSize];
	DWORD readedSize;
	string result;
	while (true)
	{
		if(!ReadFile(
			pipeReadHandle, 
			buffer, 
			bufferSize,
			&readedSize, 
			NULL))
		{
			throw std::runtime_error("Read data from pipe error");
		}
		result.append(buffer, readedSize);
		if(readedSize != bufferSize)
			break;
	}

	stringstream strStream(result);
	string ip;
	while(!strStream.eof())
	{
		getline(strStream, result);
		if (result.find("IP Address") != string::npos)
		{
			string::size_type colonPos = result.find(':');
			ip = result.substr(colonPos + 2);
			hostIPList.push_back(ip);
		}
	}
}